package net.techwatch.gwt.httprequest.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Gwt_httprequest implements EntryPoint, ClickHandler, KeyUpHandler {

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button displayButton = new Button("Display");

		displayButton.addClickHandler(this);
		displayButton.addKeyUpHandler(this);
		
		RootPanel.get("button").add(displayButton);
	}

	@Override
	public void onClick(ClickEvent event) {
		displayMessage();
		
	}

	@Override
	public void onKeyUp(KeyUpEvent event) {
		if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			displayMessage();
		}
		
	}
	
	private void displayMessage() {
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + "hello.html");
		try {
		builder.sendRequest(null, new RequestCallback() {
		
			@Override
			public void onResponseReceived(Request request, Response response) {
				String content = response.getText();
				RootPanel.get("message").add(new HTML(content));
			}
		
			@Override
			public void onError(Request request, Throwable exception) {
				GWT.log("Error on request", exception);
			}
		});
		} catch(RequestException e) {
			GWT.log("Error while requesting ressource", e);
		}
	}
}
